﻿Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Runtime.Remoting.Messaging
Imports System.Workflow.ComponentModel
Imports System.Workflow.Runtime

Namespace System.Workflow.Activities
    <Serializable> _
    Friend NotInheritable Class FollowerQueueCreator
        Implements IActivityEventListener([Of] QueueEventArgs)
        ' Methods
        Friend Sub New(ByVal operation As String)
            Me.followerOperation = operation
        End Sub

        Public Overrides Function Equals(ByVal obj As Object) As Boolean
            If (obj Is Nothing) Then
                Return False
            End If
            Dim creator As FollowerQueueCreator = [TryCast](obj,FollowerQueueCreator)
            Return (Me.followerOperation = creator.followerOperation)
        End Function

        Public Overrides Function GetHashCode() As Integer
            Return Me.followerOperation.GetHashCode
        End Function

        Private Sub System.Workflow.ComponentModel.IActivityEventListener<System.Workflow.ComponentModel.QueueEventArgs>.OnEvent(ByVal sender As Object, ByVal args As QueueEventArgs) Implements IActivityEventListener([Of] QueueEventArgs).OnEvent
            SyncLock Me.sync
                Dim queue As WorkflowQueue = DirectCast(sender, WorkflowQueue)
                Dim queueName As EventQueueName = DirectCast(queue.QueueName, EventQueueName)
                WorkflowActivityTrace.Activity.TraceEvent(TraceEventType.Information, 0, "FollowerQueueCreator: initialized on operation {0} for follower {1}", New Object() { (queueName.InterfaceType.Name & queueName.MethodName), Me.followerOperation })
                Dim message As IMethodMessage = [TryCast](queue.Peek,IMethodMessage)
                Dim propertyValues As ICollection([Of] CorrelationProperty) = CorrelationResolver.ResolveCorrelationValues(queueName.InterfaceType, queueName.MethodName, message.Args, False)
                Dim name2 As New EventQueueName(queueName.InterfaceType, Me.followerOperation, propertyValues)
                If Not queue.QueuingService.Exists(name2) Then
                    WorkflowActivityTrace.Activity.TraceEvent(TraceEventType.Information, 0, "FollowerQueueCreator::CreateQueue creating q {0}", New Object() { name2.GetHashCode })
                    queue.QueuingService.CreateWorkflowQueue(name2, True)
                End If
            End SyncLock
        End Sub


        ' Fields
        Private followerOperation As String
        Private sync As Object = New Object
    End Class
End Namespace

